﻿using FreeSql;
using FreeSql.Internal;
using System.Data;
using System.Diagnostics;

namespace D.AT.Extensions
{
    public static class OrmFactory
    {
        public static string Name = null;
        public static IFreeSql SpcOracle;
        public static IFreeSql MesOracle;
        public static IFreeSql MySqllite;

        /// <summary>
        /// 添加ORM以及数据库
        /// </summary>
        /// <param name="services"></param>
        /// <param name="env"></param>
        /// <param name="dbConfig"></param>
        public static async Task<int> AddFreeSql(string name, string mesConnectionString, string spcConnectionString)
        {
            try
            {
                if (string.IsNullOrEmpty(spcConnectionString))
                {
                    return 2;
                }
                if (!string.IsNullOrEmpty(Name) && name == Name)
                {
                    return 0;
                }
                Name = name;

                // SPC DB
                var spc = GetFreeSqlBuilder(DataType.Oracle, spcConnectionString);
                SpcOracle = spc.Build();

                // 获取数据库连接状态
                var spcConnStatus = await SpcOracle.Ado.ExecuteConnectTestAsync();
                if (!spcConnStatus)
                {
                    return 1;
                }
                WriteSqlLog(spc, SpcOracle);
                // MES DB
                if (!string.IsNullOrEmpty(mesConnectionString))
                {
                    var mes = GetFreeSqlBuilder(DataType.Oracle, mesConnectionString);
                    MesOracle = mes.Build();

                    // 获取数据库连接状态
                    var mesConnStatus = await MesOracle.Ado.ExecuteConnectTestAsync();
                    if (!mesConnStatus)
                    {
                        return 2;
                    }
                    WriteSqlLog(mes, MesOracle);
                }
               
                return 0;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        public static int AddMyFreeSql(string cacheConnectionString)
        {
            try
            {
                if (string.IsNullOrEmpty(cacheConnectionString))
                {
                    return 3;
                }
                // CACHE DB
                var cache = GetFreeSqlBuilder(DataType.Sqlite, cacheConnectionString, true);
                MySqllite = cache.Build();

                // 获取数据库连接状态 
                if (!MySqllite.Ado.ExecuteConnectTest())
                {
                    return -1;
                }
                WriteSqlLog(cache, MySqllite);
                return 0;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }


        private static FreeSqlBuilder GetFreeSqlBuilder(DataType dataType, string connection, bool useAutoSyncStructure = false)
        {
            var freeSqlBuilder = new FreeSqlBuilder();
            freeSqlBuilder.UseNameConvert(NameConvertType.ToUpper)
                   .UseConnectionString(dataType, connection)
                   .UseAutoSyncStructure(useAutoSyncStructure) //自动迁移实体的结构到数据库
                                                               //.UseLazyLoading(false)
                   .UseNoneCommandParameter(true);

            return freeSqlBuilder;
        }

        private static void WriteSqlLog(FreeSqlBuilder freeSqlBuilder, IFreeSql freeSql)
        {
            // 监听所有命令
            freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) =>
            {
                Trace.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n");
            });

            // 监听Curd操作
            freeSql.Aop.CurdBefore += (s, e) =>
            {
                Trace.WriteLine($"{e.Sql}\r\n");
            };
        }

        private static DataType GetDbType(int dataType)
        {
            if (dataType == 0)
            {
                return DataType.MySql;
            }
            else if (dataType == 1)
            {
                return DataType.SqlServer;
            }
            else if (dataType == 2)
            {
                return DataType.PostgreSQL;
            }
            else if (dataType == 3)
            {
                return DataType.Oracle;
            }
            else if (dataType == 4)
            {
                return DataType.Sqlite;
            }
            else if (dataType == 5)
            {
                return DataType.OdbcOracle;
            }
            else if (dataType == 6)
            {
                return DataType.OdbcSqlServer;
            }
            else if (dataType == 7)
            {
                return DataType.OdbcMySql;
            }
            else if (dataType == 8)
            {
                return DataType.OdbcPostgreSQL;
            }
            else if (dataType == 9)
            {
                return DataType.Odbc;
            }
            else if (dataType == 10)
            {
                return DataType.OdbcDameng;
            }
            else if (dataType == 11)
            {
                return DataType.MsAccess;
            }
            else if (dataType == 12)
            {
                return DataType.Dameng;
            }
            else if (dataType == 13)
            {
                return DataType.OdbcKingbaseES;
            }
            else if (dataType == 14)
            {
                return DataType.ShenTong;
            }
            else if (dataType == 15)
            {
                return DataType.KingbaseES;
            }
            else if (dataType == 16)
            {
                return DataType.Firebird;
            }
            else
            {
                return DataType.Custom;
            }

        }
    }
}
